use std::{collections::HashMap, fs::File, io::Read};

use log::info;
use serde_derive::Deserialize;

#[derive(Debug)]
pub struct Conf {
    ser_map: HashMap<String, ConfItem>,
}
#[derive(Debug, Deserialize)]
pub struct ConfItem {
    name: String,
    offline_interval: i32,
    start_type: String,
    start_cmd: String,
}
impl ConfItem {
    pub fn get_offline_interval(&self) -> i32 {
        self.offline_interval
    }
    pub fn get_start_cmd(&self) -> &str {
        &self.start_cmd
    }
    pub fn get_start_type(&self) -> &str {
        &self.start_type
    }
}
#[derive(Deserialize, Debug)]
struct AppConf {
    service: Vec<ConfItem>,
}

impl Conf {
    pub fn new() -> Self {
        let file_path = "./app.toml";
        info!("load config file {}", file_path);
        let mut file = match File::open(file_path) {
            Ok(f) => f,
            Err(e) => panic!("open file failed {} : {}", file_path, e),
        };
        let mut toml_str = String::new();
        match file.read_to_string(&mut toml_str) {
            Ok(len) => println!("read file size: {}", len),
            Err(e) => panic!("read file failed {}", e),
        };
        let c: Result<AppConf, toml::de::Error> = toml::from_str(toml_str.as_str());
        let app_conf = match c {
            Ok(d) => d,
            Err(e) => {
                panic!("{}", e);
            }
        };
        let mut smap = HashMap::new();
        for item in app_conf.service {
            smap.insert(item.name.clone(), item);
        }

        info!("服务监控配置信息:{:?}", &smap);
        Conf { ser_map: smap }
    }
    pub fn get_conf(&self) -> &HashMap<String, ConfItem> {
        &self.ser_map
    }
}

#[test]
pub fn toml_test() {
    let file_path = "./app.toml";
    let mut file = match File::open(file_path) {
        Ok(f) => f,
        Err(e) => panic!("open file failed {} : {}", file_path, e),
    };
    let mut toml_str = String::new();
    match file.read_to_string(&mut toml_str) {
        Ok(len) => println!("read file size: {}", len),
        Err(e) => panic!("read file failed {}", e),
    };
    let c: Result<AppConf, toml::de::Error> = toml::from_str(toml_str.as_str());
    println!("{:?}", &c);
}
